﻿CREATE PROCEDURE [dbo].[usp_FinalizeBatchResubmission]
	@Debug	bit = 0
AS

	IF @Debug = 1
	BEGIN
		print 'sp_BuildBatchForResubmission: @vCurrentTime = ' + CONVERT(varchar(50), GETDATE())
	END
	
	-- Mark the Batch as Complete if there are no Pending BatchMessages
	BEGIN TRY
	
		UPDATE br SET
			[EndDatetime] = GETDATE()
			, [Status] = N'Completed'
			, [LastModified] = GETDATE()
			, [LastModifiedBy] = SYSTEM_USER
		FROM
			[BatchResubmission] br
		WHERE
			br.[Status] = N'Processing'
			AND NOT EXISTS(SELECT TOP 1 1 FROM BatchResubmissionMessage brm WHERE br.BatchID = brm.MessageBatchID AND brm.[Status] = N'Processing')
		
	END TRY
	BEGIN CATCH
		DECLARE @error int, @message varchar(4000), @xstate int;
        SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();

        
		RAISERROR ('[[usp_FinalizeBatchResubmission]]: %d: %s', 16, 1, @error, @message) ;
        RETURN;
	END CATCH

RETURN 0
